package com.heihei.security.controller;

import com.heihei.security.dto.auth.UserDto;
import com.heihei.security.model.auth.AuthenticationRequest;
import com.heihei.security.service.auth.AuthenticationService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * 登录Controller
 *
 * @author duanhengfei
 * @version 1.0
 * @date 2020/6/27 18:10
 * @since JDK1.8
 */
@RestController
public class LoginController {
    @Resource
    private AuthenticationService authenticationService;

    @PostMapping(value = "/login", produces = {"text/plain;charset=UTF-8"})
    public String login(AuthenticationRequest authenticationRequest, HttpSession session) {
        UserDto authentication = authenticationService.authentication(authenticationRequest);
        //加入session
        session.setAttribute(UserDto.SESSION_USER_KEY, authentication);
        return authenticationRequest.getUsername() + "登录成功";
    }

    /**
     * 访问资源（获取session）测试
     *
     * @author duanhengfei
     * @date 2020年06月27日 18:42:24
     */
    @GetMapping(value = "/resource/r1", produces = {"text/plain;charset=UTF-8"})
    public String test01(HttpSession session){
        String fullName = null;
        UserDto user = (UserDto)session.getAttribute(UserDto.SESSION_USER_KEY);
        if(user == null) {
            fullName = "匿名 ";
        } else {
            fullName = user.getFullName();
        }
        return fullName + "访问资源r1";
    }

    /**
     * 访问资源（获取session）测试
     *
     * @author duanhengfei
     * @date 2020年06月27日 18:42:24
     */
    @GetMapping(value = "/resource/r2", produces = {"text/plain;charset=UTF-8"})
    public String test02(HttpSession session){
        String fullName = null;
        UserDto user = (UserDto)session.getAttribute(UserDto.SESSION_USER_KEY);
        if(user == null) {
            fullName = "匿名 ";
        } else {
            fullName = user.getFullName();
        }
        return fullName + "访问资源r2";
    }

    /**
     * 退出登录
     *
     * @author duanhengfei
     * @date 2020年06月27日 18:50:28
     */
    @GetMapping(value = "/logout", produces = {"text/plain;charset=UTF-8"})
    public String logout(HttpSession session) {
        String fullName = null;
        UserDto user = (UserDto)session.getAttribute(UserDto.SESSION_USER_KEY);
        if(user != null){
            fullName = user.getFullName();
        }
        if(fullName != null) {
            session.invalidate();
        }
        return "当前用户已退出";
    }

}